// 商品模块
export default {
  namespaced: true, // 启用命名空间
  
  state: {
    name: '默认商品',
    price: 0,
    category: '默认分类',
    inventory: 100
  },
  
  getters: {
    // 获取商品信息摘要
    productSummary(state) {
      return `${state.name} - ￥${state.price} (${state.inventory}件库存)`
    },
    
    // 根据价格判断商品等级
    priceLevel(state) {
      if (state.price > 10000) return '高端商品'
      if (state.price > 1000) return '中端商品'
      return '入门商品'
    }
  },
  
  mutations: {
    // 设置商品名称
    setName(state, name) {
      state.name = name
    },
    
    // 设置商品价格
    setPrice(state, price) {
      state.price = price
    },
    
    // 更新库存
    updateInventory(state, quantity) {
      state.inventory = quantity
    },
    
    // 增加库存
    addInventory(state, quantity) {
      state.inventory += quantity
    }
  },
  
  actions: {
    // 异步获取商品信息
    async fetchProductInfo({ commit }, productId) {
      // 模拟 API 调用
      return new Promise((resolve) => {
        setTimeout(() => {
          const productData = {
            name: `商品${productId}`,
            price: Math.floor(Math.random() * 10000),
            category: '电子产品',
            inventory: Math.floor(Math.random() * 100)
          }
          commit('setName', productData.name)
          commit('setPrice', productData.price)
          commit('updateInventory', productData.inventory)
          resolve(productData)
        }, 1000)
      })
    },
    
    // 异步更新库存
    async updateInventoryAsync({ commit }, { quantity, isAdd = false }) {
      // 模拟 API 调用
      return new Promise((resolve) => {
        setTimeout(() => {
          if (isAdd) {
            commit('addInventory', quantity)
          } else {
            commit('updateInventory', quantity)
          }
          resolve({ success: true })
        }, 500)
      })
    }
  }
}